package com.mantbox.channelcall.utils;

import com.mantbox.channelcall.entity.UrlLink;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Component
public class DatabaseUtil {
    //驱动
    public static final String mysqlDrive = "com.mysql.cj.jdbc.Driver";
    //数据库
    public static final String mysqlURL = "jdbc:mysql://127.0.0.1:3306/advchannel?serverTimezone=UTC";
    //用户名
    public static final String mysqlusername = "root";
    public static final String mysqlpassword = "LMX123!@#";


    public void updateUrlStatus(List<UrlLink> list) {
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            Class.forName(mysqlDrive);
            conn = DriverManager.getConnection(mysqlURL,mysqlusername,mysqlpassword);
            conn.setAutoCommit(false);
            String sql = "update url_link SET click_count=?,fail_count=? WHERE id=?";
            pstm = conn.prepareStatement(sql);

            for (UrlLink urlLink : list) {
                pstm.setInt(1,urlLink.getClickCount());
                pstm.setInt(2,urlLink.getFailCount());
                pstm.setInt(3,urlLink.getId());
                pstm.executeUpdate();
            }
            conn.commit();
        }catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }finally {
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
